package org.scboy.dbms.detect;

import java.util.ArrayList;
import java.util.List;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.BaseAppServerDao;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 微服务心跳检测
 */
@Configuration
@EnableScheduling
public class MicroserviceDetect  implements ApplicationListener<ApplicationReadyEvent>{
	
	Log log=LogFactory.get();
	
	@Autowired
	EntityFactory factory;
	
	
	private static List<Model> MICROSERVICES=new ArrayList<Model>();
	

	/**
	 * 每30秒同步一次微服务列表
	 */
	@Scheduled(cron = "0/30 * * * * ?")
	private void load() {
		BaseAppServerDao dao=factory.getDao(BaseAppServerDao.class);
		MICROSERVICES=dao.select(Model.create().addNrc("serverMsg"));
	}
	
	/**
	 * 每10秒检测一次微服务状态
	 */
	@Scheduled(cron = "0/10 * * * * ?")
	private void detect() {
		BaseAppServerDao dao=factory.getDao(BaseAppServerDao.class);
		for (Model microservice : MICROSERVICES) {
			
			//只检查已经启动的项目
			if(dao.count(Model.create().add("id", microservice.getString("id")).add("status", 2))>0) {
				try {
					String ip=microservice.getString("ip");
					String port=microservice.getString("port");
					String result=HttpUtil.get("http://"+ip+":"+port+"/actuator/health");
					JSONObject resObj=new JSONObject(result);
					if("UP".equals(resObj.getStr("status"))) {
						dao.update(
							Model.create()
							.add("id", microservice.getString("id"))
							.add("status", 2)
							.add("serverMsg","")
						);
					}else {
						dao.update(
							Model.create()
							.add("id", microservice.getString("id"))
							.add("status", 0)
							.add("serverMsg",resObj.getStr("status"))
						);
					}
				} catch (Exception e) {
					dao.update(
						Model.create()
						.add("id", microservice.getString("id"))
						.add("status", 0)
						.add("serverMsg", ExceptionUtil.stacktraceToString(e))
					);
				}
			}
		}
	}
	
	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {
		load();
	}
	
}
